<template>
  <view class="root">
    <!-- 切换已上架和未上架活动 -->
    <view class="tab fixed-tab">
      <view :class="{ active: isListed }" @click="toggleTab(true)">已上架</view>
      <view :class="{ active: !isListed }" @click="toggleTab(false)">未上架</view>
    </view>

    <!-- 活动列表 -->
    <scroll-view class="activity-list" scroll-y @scrolltolower="loadMore">
      <view v-for="item in activities" :key="item.activityId" class="info" @click="goToActivityDetail(item.activityId)">
        <view class="info-text">
          <p class="title">{{ item.title }}</p>
          <p class="time">{{ formatTime(item.releaseTime) }}</p>
          <!-- 显示审核状态 -->
          <p v-if="item.isOnline === 2"></p>
          <p v-else-if="item.status === 2" style="color: forestgreen;">审核通过</p>
          <p v-else-if="item.status === 1" style="color: orangered;">审核中</p>
          <p v-else-if="item.status === 3" style="color: red;">审核失败</p>
        </view>
        <view class="button-group">
          <!-- 上架和下架按钮 -->
          <button v-if="item.isOnline === 2" @click.stop="changeStatus(item, false)">下架</button>
          <button v-else-if="item.status === 2" @click.stop="changeStatus(item, true)">上架</button>
          <button v-else @click.stop="deleteActivity(item.activityId)">删除</button>
        </view>
      </view>
    </scroll-view>

    <!-- 添加活动按钮 -->
    <view class="add" @click="addActivity">+ 添加活动</view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getToken } from '@/utils/auth';

const isListed = ref(true); // 判断是否是已上架活动
const activities = ref([]); // 存储活动数据
const pageNum = ref(1);
const pageSize = ref(10);
const merchantId = ref(1); // 假设商户ID为1，可动态获取

// 切换已上架和未上架活动
const toggleTab = (listed) => {
  isListed.value = listed;
  pageNum.value = 1;
  activities.value = [];
  loadActivities();
};

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 加载活动数据
const loadActivities = () => {
  const url = isListed.value 
    ? `http://localhost:8866/sn/activities/online/${merchantId.value}` 
    : `http://localhost:8866/sn/activities/offline/${merchantId.value}`;
  const token = getToken();
  uni.request({
    url,
    method: 'GET',
    header: { 'Authorization': token },
    data: { pageNum: pageNum.value, pageSize: pageSize.value },
    success: (response) => {
      const { data } = response;
      if (data && data.data.records) {
        activities.value = [...activities.value, ...data.data.records];
      }
    },
    fail: (error) => {
      console.error('请求失败:', error);
    }
  });
};

// 加载更多活动数据
const loadMore = () => {
  pageNum.value++;
  loadActivities();
};

// 修改活动状态（上架/下架）
const changeStatus = (item, status) => {
  const url = status 
    ? `http://localhost:8866/sn/activities/online/${item.activityId}` 
    : `http://localhost:8866/sn/activities/offline/${item.activityId}`;

  const token = getToken();
  uni.request({
    url,
    method: 'PUT',
    header: { 'Authorization': token },
    success: (response) => {
      if (response.data.code === 200) {
        uni.showToast({ title: status ? '上架成功' : '下架成功', icon: 'success' });
        // 重新加载活动列表
        pageNum.value = 1;
        activities.value = [];
        loadActivities();
      } else {
        uni.showToast({ title: response.data.msg, icon: 'none' });
      }
    },
    fail: () => {
      uni.showToast({ title: '操作失败，请重试', icon: 'none' });
    }
  });
};


// 删除活动
const deleteActivity = (id) => {
  uni.showModal({
    title: '确认删除',
    content: '删除后无法恢复，确定要删除该活动吗？',
    success: (res) => {
      if (res.confirm) {
        const url = `http://localhost:8866/sn/activities/delete/${id}`;
        const token = getToken();
        uni.request({
          url,
          method: 'DELETE',
          header: { 'Authorization': token },
          success: (response) => {
            if (response.data.code === 200) {
              activities.value = activities.value.filter(a => a.activityId !== id);
              uni.showToast({ title: '删除成功', icon: 'success' });
            } else {
              uni.showToast({ title: response.data.msg, icon: 'none' });
            }
          },
          fail: () => {
            uni.showToast({ title: '删除失败，请重试', icon: 'none' });
          }
        });
      }
    }
  });
};

// 添加活动
const addActivity = () => {
  uni.navigateTo({
    url: '/pages/work/activity_publish/activity_add/activity_add'
  });
};

// 跳转到活动详情
const goToActivityDetail = (activityId) => {
  uni.navigateTo({
    url: `/pages/work/activity_publish/activity_detail/activity_detail?activityId=${activityId}`
  });
};

// 初始加载
onMounted(() => {
  loadActivities();
});
</script>

<style>
.root {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 10px;
  background: #f8f9fa;
}

.fixed-tab {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: #ffffff;
  z-index: 1000;
  padding: 10px 0;
  display: flex;
  justify-content: space-around;
  border-bottom: 2px solid #ddd;
}

.active {
  font-weight: bold;
  color: #007aff;
  border-bottom: 2px solid #007aff;
}

.activity-list {
  flex: 1;
  overflow-y: auto;
  margin-top: 60px;
  padding-bottom: 80px;
}

.info {
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #ddd;
  background: white;
  margin: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group button {
  margin-left: 5px;
  padding: 8px 12px;
  border: none;
  background: #007aff;
  color: white;
  border-radius: 5px;
}

.add {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #007aff;
  color: white;
  padding: 12px 24px;
  border-radius: 30px;
  font-size: 18px;
}
</style>
